﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using ContractorTimesheet.DataModel;

namespace ContractorTimesheet.Repository
{
    public class LeaveRepository : BaseRepository
    {
        TimesheetDBModel dataModel = new TimesheetDBModel();

        public IList<Leave> GetAllLeaves()
        {
            return dataModel.Leaves.ToList();
        }

        public IList<Leave> GetLeaves(int userId)
        {
            return dataModel.Users.Single(m => m.Id == userId).Leaves.ToList();
        }

        public IList<Leave> GetLeaves(int userId, int month, int year)
        {
            return GetLeaves(userId).Where(m => int.Parse(m.Month) == month && int.Parse(m.Year) == year).ToList();
        }

        public void Add(Leave leave)
        {
            try
            {
                dataModel.Leaves.Add(leave);

                dataModel.SaveChanges();

            }
            catch (DbEntityValidationException ex)
            {
                throw new Exception(GetErrorMessage(ex));
            }
        }

        public async void DeleteAsync(int id)
        {
            Leave leave = dataModel.Leaves.Single(o => o.Id == id);

            dataModel.Leaves.Remove(leave);

            await dataModel.SaveChangesAsync();
        }
    }
}